/*
 * Created on 04/11/2006
 */
package com.minotauro.i18n.base;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Demián Gutierrez
 */
public class DefaultMessageFactory implements MessageFactory {

  protected static final Logger log = LoggerFactory.getLogger( //
      DefaultMessageFactory.class.getName());

  public DefaultMessageFactory() {
    // Empty
  }

  // --------------------------------------------------------------------------------

  public String locateValue(Locale defaultLocale, String res, String key) //
      throws MessageException {

    // ----------------------------------------
    // Locale from interface (default if null)
    // ----------------------------------------

    Locale currentLocale = getLocale();

    if (currentLocale == null) {
      currentLocale = defaultLocale;
    }

    // ----------------------------------------
    // Bundle for locale (use default if fail)
    // ----------------------------------------

    ResourceBundle bundle;

    try {
      log.debug("trying to locate " + res + " in locale " + currentLocale
          + " with class loader " + getClass().getClassLoader());
      bundle = ResourceBundle.getBundle(res, currentLocale, getClass()
          .getClassLoader());
    } catch (MissingResourceException e) {
      log.debug("trying to locate " + res + " in locale " + defaultLocale
          + " with class loader " + getClass().getClassLoader());
      bundle = ResourceBundle.getBundle(res, defaultLocale, getClass()
          .getClassLoader());
    }

    return bundle.getString(key);
  }

  // --------------------------------------------------------------------------------

  public Locale getLocale() //
      throws MessageException {

    return Locale.getDefault();
  }
}
